package com.lifo.order.service.serviceimpl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lifo.order.bean.HfOrder;
import com.lifo.order.dao.HfOrderMapper;
import com.lifo.order.service.HfOrderService;
import com.lifo.utils.common.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

/**
 * Created by Administrator on 2018/6/30.
 */
@Slf4j
@Service
public class HfOrderServiceImpl implements HfOrderService {


    @Autowired
    private HfOrderMapper hfOrderMapper;


    @Override
    public PageInfo<HfOrder> searchUserOrder(Integer userId, Integer currentPage, Integer pageSize) {
     Page page = PageHelper.startPage(currentPage, pageSize);
     List<HfOrder> hfOrders = hfOrderMapper.searchUserOrder(userId);
        //pageHelper无法获取总条数，所以增加手动设置 begin
        PageInfo<HfOrder> pageInfo = new PageInfo<HfOrder>(page.getResult());
        pageInfo.setList(hfOrders);
        //pageHelper无法获取总条数,所以增加手动设置 end
        return pageInfo;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public Integer saveUserOrder(List<HfOrder> hfOrders) {
        try{
            for (HfOrder hfOrder : hfOrders){
                hfOrder.setCreateTime(DateUtil.getNowDateString());
                hfOrder.setCreateDate(DateUtil.getNowDateString("yyyy-MM-dd"));
                  hfOrderMapper.saveUserOrder(hfOrder);
            }
            return 1;
        }catch (Exception e){
            log.error("保存订单发生错误：异常信息为=============>{}",e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public Boolean updateUserOrder(HfOrder hfOrder) {
        try{
            hfOrderMapper.updateUserOrder(hfOrder);
            return  true;
        }catch (Exception e){
            log.error("保存个订单时发生错误：异常信息为=============>{}",e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public HfOrder searchHfOrderByCartId(int cartId) {
        return hfOrderMapper.searchHfOrderByCartId(cartId);
    }
}
